package com.syyc.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.syyc.pojo.Content;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author huimin
 * @date 2021/10/27
 * @apiNote
 */
@SuppressWarnings("all")
public class MyApp {
    public static void main(String[] args) throws IOException {
        int imageNum = 1;//统计图片数量
        int pageSize = 172;//总页数
        int curRow = 1;

        // excel标题
        String[] title = {"名称", "类型", "集数"};

        // excel文件名
        String fileName = "B站热播番剧表.xls";

        // sheet名
        String sheetName = "B站热播番剧";

        // 创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, null, null);

        File dir = new File("g://excel/");

        if (!dir.exists()) {
            dir.mkdirs();
        }

        fileName = dir + File.separator + fileName;

        BufferedOutputStream bw = new BufferedOutputStream(new FileOutputStream(fileName));

        // 第二步，从wb中获取sheet
        HSSFSheet sheet = wb.getSheet(sheetName);

        // 第四步，创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle style = wb.createCellStyle();        // 创建一个居中格式
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style.setBorderBottom(HSSFCellStyle.BORDER_DOTTED);//下边框
        style.setBorderLeft(HSSFCellStyle.BORDER_DOTTED);//左边框
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框‘

        HSSFFont f  = wb.createFont();
        f.setFontHeightInPoints((short) 16);//字号
        f.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);//加粗
        style.setFont(f);

        //9.调整单元格宽度
        sheet.setColumnWidth(0,252*100+323);
        sheet.setColumnWidth(1,252*15+323);
        sheet.setColumnWidth(2,252*15+323);

        for (int page = 1; page <= pageSize; page++) {

            String url = "https://api.bilibili.com/pgc/season/index/result?season_version=-1&area=-1&is_finish=-1&copyright=-1&season_status=-1&season_month=-1&year=-1&style_id=-1&order=3&st=1&sort=0&page="
                    + page + "&season_type=1&pagesize=20&type=1";

            Document document = null;
            try {
                document = Jsoup.connect(url).timeout(3000).ignoreContentType(true).get();
            } catch (IOException e) {
                e.printStackTrace();
                System.err.println("解析url失败");
            }

            //转换为JSON
            JSONObject jsonObject = JSON.parseObject(document.text());

            List<Content> contentList = JSONObjectToCoverList(jsonObject);
            for (Content content : contentList) {
                ExcelUtil.setCellValue(sheet, content, style, curRow++);
            }
            System.err.println("-------第 " + page + " 页视频爬取完成");

        }

        wb.write(bw);

        // 必须关闭，否则文件损坏无内容
        bw.close();
    }


    public static InputStream createUrlConnection(String cover) {
        InputStream inputStream = null;
        try {
            URL imgUrl = new URL(cover);
            URLConnection urlConnection = imgUrl.openConnection();
            urlConnection.setConnectTimeout(10 * 1000);
            inputStream = urlConnection.getInputStream();

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("URL创建失败");
        }
        return inputStream;

    }

    //流转换
    public static void inputStreamToFile(InputStream inputStream, String imagePath) {
        System.out.println("开始转换图片");
        try {
            BufferedInputStream bis = new BufferedInputStream(inputStream);
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(imagePath));
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = bis.read(bytes)) != -1) {
                bos.write(bytes, 0, len);
            }
            bis.close();
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("inputStream转换异常");
        }

    }

    //创建图片路径
    private static String createImagePath(String cover) {
        System.out.println("开始创建图片路径");
        //图片名称
        String imgName = cover.substring(cover.lastIndexOf("/") + 1);
        //创建路径
        String path = "G://BiliBili//images";
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String fileName = dir + File.separator + imgName;
        System.out.println("图片路径：" + fileName);
        return fileName;
    }

    // 把json转化为只含有 链接 的集合
    public static List<Content> JSONObjectToCoverList(JSONObject jsonObject) {
        List<Content> coverList = new ArrayList<>();
        JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("list");
        for (int i = 0; i < jsonArray.size(); i++) {
            Map<String, String> map = (Map) jsonArray.get(i);
            coverList.add(new Content(map.get("title"),map.get("badge"),map.get("index_show")));
        }

        return coverList;
    }
}
